package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.HttpUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.annotation.RequiresPermissions;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (cartCheckedList.getCode() == R.FAIL) {
            throw new ServiceException(cartCheckedList.getMsg());
        }
        if (CollectionUtils.isEmpty(cartCheckedList.getData())) {
            throw new ServiceException("购物车无选中商品");
        }
        //将集合泛型从购物车改为订单明细
        List<OrderItem> orderItemList = cartCheckedList.getData().stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).collect(Collectors.toList());
        BigDecimal totalAmount = new BigDecimal(0);
        //订单总金额
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //渲染订单确认页面 生成用户流水号
        String tradeNo = generateTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        String tradeNo = orderForm.getTradeNo();
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long isFlag =(Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNo);
        if(isFlag == 0){
            throw new ServiceException("请勿重复提交订单");
        }
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if(CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("订单集合不能为空");
        }
        //验证购物车价格与最新价格是否一致
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if(skuPriceListR.getCode() == HttpStatus.ERROR){
            throw new ServiceException(skuPriceListR.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListR.getData();
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(
                SkuPrice::getSkuId,
                SkuPrice::getSalePrice
        ));

        StringBuilder stringBuilder = new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            BigDecimal salePrice = skuIdToSalePriceMap.get(orderItem.getSkuId());
            if(orderItem.getSkuPrice().compareTo(salePrice) != 0){
                stringBuilder.append(orderItem.getSkuName()).append("价格有变动;");
            }
        }
        if(StringUtils.hasText(stringBuilder.toString())){
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(stringBuilder.toString());
        }

        //检查库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(item -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(item.getSkuId());
            skuLockVo.setSkuNum(item.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());

//        String checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER).getData();
        R<String> checkAndLockResultR = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);

        if(checkAndLockResultR.getCode() == HttpStatus.ERROR){
            throw new ServiceException(checkAndLockResultR.getMsg());
        }

        String checkAndLockResult = checkAndLockResultR.getData();
        if(StringUtils.hasText(checkAndLockResult)){
            throw new ServiceException(checkAndLockResult);
        }

        //保存订单数据
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        }catch (Exception e){
            e.printStackTrace();
            //解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());

            throw new ServiceException("下单失败");
        }
        //从购物车中删除下单的商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);

        //发送延迟消息，取消订单
        rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(orderInfo != null && orderInfo.getOrderStatus().intValue() ==0){
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("超时未支付");
            orderInfo.setOrderStatus(-1);
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderId);
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }


    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if(orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm){
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        //保存订单对象
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        System.out.println("远程调用 ---> remoteUserAddressService.getUserAddress");
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        System.out.println("调用结束 ---> remoteUserAddressService.getUserAddress");
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);

        //保存多个订单项
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

    //验证提交的流水号是否有效
    private Boolean checkTradeNo(String userId, String tradeNo){
        String userTradeKey = "user:tradeNo:" + userId;
        String cacheTradeKey = (String) redisTemplate.opsForValue().get(userTradeKey);
        return tradeNo.equals(cacheTradeKey);
    }

    private String generateTradeNo(Long userId){
        //构建流水号key
        String userTradeKey = "user:tradeNo:" + userId;
        //构建流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-","");
        //将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }

    private void deleteTradeNo(String userId){
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }

}